package com.why.service.iml;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;

import com.why.service.VodService;
import com.why.servicebase.exception.GuilException;
import com.why.utils.AliyunVodSDKUtils;
import com.why.utils.ConstantPropertiesUtil;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: guli_parent
 * @description:
 * @author: @why
 * @create: 2021-02-06 14:30
 **/
@Service
@Slf4j
public class VodServiceImpl implements VodService {
    @Override
    public String uploadToAliyun(MultipartFile videoFile) {
        try {
            InputStream inputStream = videoFile.getInputStream();
            String originalFilename = videoFile.getOriginalFilename();
            String title = originalFilename.substring(0, originalFilename.lastIndexOf("."));

            /**
             * title:阿里云那里显示的名字
             * filename:文件上传时候的名字
             * inputStream：输入的流
             */
            //new出一个上传的请求流
            UploadStreamRequest request = new UploadStreamRequest(
                    ConstantPropertiesUtil.ACCESS_KEY_ID,
                    ConstantPropertiesUtil.ACCESS_KEY_SECRET,
                    title, originalFilename, inputStream);

            //new一个上传的上传者
            UploadVideoImpl uploader = new UploadVideoImpl();
            //new一个响应的对象
            UploadStreamResponse response = uploader.uploadStream(request);

            //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。
            // 其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
            String videoId = response.getVideoId();
            if (!response.isSuccess()) {
                String errorMessage = "阿里云上传错误：" + "code：" + response.getCode() + ", message：" + response.getMessage();
                log.warn(errorMessage);
                if (StringUtils.isEmpty(videoId)) {
                    throw new GuilException(20001, errorMessage);
                }
            }
            //返回上传成功后的id值
            return videoId;
        } catch (IOException e) {
            throw new GuilException(20001, "guli vod 服务上传失败");
        }

    }

    /**
     * 删除视频根据id
     * @param id
     */

    @Override
    public void deleteVideoById(String id) {
        try {
            //得到初始化对象
            DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(
                    ConstantPropertiesUtil.ACCESS_KEY_ID,
                    ConstantPropertiesUtil.ACCESS_KEY_SECRET);
            //发送删除请求
            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(id);
            //得到删除响应
            DeleteVideoResponse response = client.getAcsResponse(request);
        } catch (ClientException e) {
            throw new GuilException(20001, "视频删除失败");
        }
    }

    /**
     * 删除多个视频根据id
     */
    @Override
    public void deleteVideoByCourseId(List<String> videoIds) {
        //将字符串按逗号分割
        // String ids = org.apache.commons.lang.StringUtils.join(videoIds.toArray(), ",");
        /**效率，数量少的时候切割字符串好用，数量大于10000的时候，工具类以微弱的优势获胜**/
 String ids = videoIds.toString().replace("[","").replace("]","").replaceAll(" ","");

        try {
            //得到初始化对象
            DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(
                    ConstantPropertiesUtil.ACCESS_KEY_ID,
                    ConstantPropertiesUtil.ACCESS_KEY_SECRET);
            //发送删除请求
            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(ids);
            //得到删除响应
            DeleteVideoResponse response = client.getAcsResponse(request);
        } catch (ClientException e) {
            throw new GuilException(20001, "视频删除失败");
        }

    }

    @Test
    public void test(){
        ArrayList<Object> list = new ArrayList<>();
        list.add("dasdasd");
//       for(int i=0;i<10000;i++){
//           list.add("dasdasd");
//       }

        long start=System.currentTimeMillis();
        System.out.println(list.toString().replace("[","").replace("]","").replaceAll(" ",""));
        System.out.println(System.currentTimeMillis()-start);

        start=System.currentTimeMillis();

        System.out.println(org.apache.commons.lang.StringUtils.join(list.toArray(), ","));
        System.out.println(System.currentTimeMillis()-start);


    }

}
